<template>
	<div class="container">
		<!-- 顶部搜索区域 -->
		<div class="search-header">
			<div class="station-switch">
				<div class="station-item" @click="showStationPicker('departure')">
					<div class="station-label">出发站</div>
					<div class="station-value">
						<span :class="{ 'placeholder': !searchForm.departure }">
							{{ searchForm.departure || '请选择' }}
						</span>
						<el-icon><ArrowDown /></el-icon>
					</div>
				</div>
				<div class="switch-btn" @click="switchStations">
					<el-icon><Switch /></el-icon>
				</div>
				<div class="station-item" @click="showStationPicker('arrival')">
					<div class="station-label">到达站</div>
					<div class="station-value">
						<span :class="{ 'placeholder': !searchForm.arrival }">
							{{ searchForm.arrival || '请选择' }}
						</span>
						<el-icon><ArrowDown /></el-icon>
					</div>
				</div>
			</div>
			
			<div class="date-picker">
				<div class="date-label">出发日期</div>
				<el-date-picker
					v-model="searchForm.departureDate"
					type="date"
					:disabled-date="disabledDate"
					@change="searchTickets"
					format="M月D日 dddd"
					value-format="YYYY-MM-DD"
					placeholder="请选择日期"
					:clearable="true"
					class="date-picker-input"
				/>
			</div>
			
			<el-button 
				type="primary" 
				class="search-btn"
				@click="searchTickets"
				>
				查找车票
			</el-button>
		</div>

		<!-- 热门路线推荐 -->
		<div class="section-title" v-if="!hasSearched">
			<span class="title-text">热门路线</span>
			<span class="title-desc">精选路线推荐</span>
		</div>
		
		<div class="hot-routes" v-if="!hasSearched">
			<div 
				v-for="route in hotRoutes" 
				:key="route.label"
				class="hot-route-item"
				@click="selectHotRoute(route)"
			>
				<div class="route-info">
					<div class="route-stations">
						<span class="from">{{ route.from }}</span>
						<el-icon class="arrow"><ArrowRight /></el-icon>
						<span class="to">{{ route.to }}</span>
					</div>
					<div class="route-tag">{{ route.label }}</div>
				</div>
				<div class="route-desc">{{ route.description }}</div>
			</div>
		</div>

		<!-- 搜索结果 -->
		<template v-if="hasSearched && tickets.length > 0">
			<div class="result-header">
				<div class="result-date">{{ formatDate(searchForm.departureDate) }}</div>
				<div class="result-count">找到 {{ tickets.length }} 个车次</div>
			</div>
			
			<div class="ticket-list">
				<div 
					v-for="ticket in tickets" 
					:key="ticket.id" 
					class="ticket-item"
				>
					<div class="ticket-main">
						<div class="time-info">
							<div class="departure">
								<div class="time">{{ ticket.departureTime }}</div>
								<div class="station">{{ ticket.departure }}</div>
							</div>
							<div class="duration">
								<div class="duration-line"></div>
								<div class="duration-text">{{ ticket.duration }}</div>
							</div>
							<div class="arrival">
								<div class="time">{{ ticket.arrivalTime }}</div>
								<div class="station">{{ ticket.arrival }}</div>
							</div>
						</div>
						
						<div class="train-info">
							<div class="train-number">
								{{ ticket.trainNumber }}
								<span class="train-type">{{ getTrainType(ticket.trainNumber) }}</span>
							</div>
							<div class="seats-info" :class="{ 'low': ticket.seats < 100 }">
								余票: {{ ticket.seats }}张
							</div>
						</div>
					</div>
					
					<div class="ticket-footer">
						<div class="price">
							<span class="price-symbol">￥</span>
							<span class="price-value">{{ ticket.price }}</span>
						</div>
						<el-button 
							type="primary"
							class="book-btn"
							@click="addToCart(ticket)"
						>
							预订
						</el-button>
					</div>
				</div>
			</div>
		</template>

		<!-- 无结果提示 -->
		<div class="empty-result" v-if="hasSearched && !tickets.length">
			<img src="/static/empty.png" class="empty-icon">
			<div class="empty-text">暂无符合条件的车票</div>
		</div>

		<!-- 购物车按钮 -->
		<div class="cart-fab" @click="navigateToCart" v-if="cartCount">
			<el-badge :value="cartCount" class="cart-badge">
				<el-icon><ShoppingCart /></el-icon>
			</el-badge>
		</div>

		<!-- 添加站点选择器弹窗 -->
		<el-dialog
			v-model="stationPickerVisible"
			:title="pickerTitle"
			width="90%"
			custom-class="station-picker-dialog"
		>
			<div class="station-picker">
				<!-- 热门城市 -->
				<div class="picker-section">
					<div class="section-title">热门城市</div>
					<div class="hot-cities">
						<div 
							v-for="city in hotCities" 
							:key="city"
							class="city-item"
							@click="selectStation(city)"
						>
							{{ city }}
						</div>
					</div>
				</div>
				
				<!-- 所有城市 -->
				<div class="picker-section">
					<div class="section-title">所有城市</div>
					<div class="city-list">
						<div 
							v-for="city in allCities" 
							:key="city"
							class="city-item"
							@click="selectStation(city)"
						>
							{{ city }}
						</div>
					</div>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useCartStore } from '@/stores/cart'
import { ticketList, hotRoutes } from '@/mock/data'
import { 
	ArrowRightBold as ArrowRight,
	SwitchButton as Switch,
	ShoppingCart,
	ArrowDown
} from '@element-plus/icons-vue'

export default {
	components: {
		ArrowRight,
		Switch,
		ShoppingCart,
		ArrowDown
	},
	setup() {
		// 初始化数据
		const searchForm = reactive({
			departure: '',
			arrival: '',
			departureDate: ''
		})
		
		const tickets = ref([])
		const allTickets = ref([])  // 初始为空数组
		const cartStore = useCartStore()
		const hasSearched = ref(false)
		
		// 在组件挂载后加载数据
		onMounted(() => {
			allTickets.value = ticketList
		})
		
		// 取推荐车票（随机选择6个不同路线的车票）
		const recommendedTickets = computed(() => {
			if (!allTickets.value.length) return []
			
			const uniqueRoutes = new Set()
			return allTickets.value
				.filter(ticket => {
					const route = `${ticket.departure}-${ticket.arrival}`
					if (!uniqueRoutes.has(route) && uniqueRoutes.size < 6) {
						uniqueRoutes.add(route)
						return true
					}
					return false
				})
				.sort((a, b) => a.price - b.price)
		})

		const selectHotRoute = (route) => {
			searchForm.departure = route.from
			searchForm.arrival = route.to
			searchTickets()
		}

		const switchStations = () => {
			const temp = searchForm.departure
			searchForm.departure = searchForm.arrival
			searchForm.arrival = temp
			if (searchForm.departure && searchForm.arrival) {
				searchTickets()
			}
		}

		const searchTickets = () => {
			if (!searchForm.departure || !searchForm.arrival) {
				uni.showToast({
					title: '请输入出发地和目的地',
					icon: 'none'
				})
				return
			}

			hasSearched.value = true
			
			// 过滤符合条件的车票
			const filteredTickets = allTickets.value.filter(ticket => {
				const departureMatch = ticket.departure.includes(searchForm.departure)
				const arrivalMatch = ticket.arrival.includes(searchForm.arrival)
				
				// 基本路线匹配
				let matches = departureMatch && arrivalMatch
				
				// 如果选择了日期，添加日期筛选
				if (searchForm.departureDate && matches) {
					const selectedDate = new Date(searchForm.departureDate)
					const today = new Date()
					
					// 如果是今天，只显示当前时间之后的车次
					if (selectedDate.toDateString() === today.toDateString()) {
						const currentTime = today.getHours() * 60 + today.getMinutes()
						const [hours, minutes] = ticket.departureTime.split(':').map(Number)
						const ticketTime = hours * 60 + minutes
						matches = ticketTime > currentTime
					}
				}
				
				return matches
			})

			// 按时间排序
			const sortedTickets = filteredTickets.sort((a, b) => {
				const [hoursA, minutesA] = a.departureTime.split(':').map(Number)
				const [hoursB, minutesB] = b.departureTime.split(':').map(Number)
				return (hoursA * 60 + minutesA) - (hoursB * 60 + minutesB)
			})

			tickets.value = sortedTickets

			// 更新提示信息
			if (sortedTickets.length === 0) {
				let message = '未找到符合条件的车票'
				if (searchForm.departureDate) {
					const dateStr = new Date(searchForm.departureDate).toLocaleDateString()
					message = `${dateStr} ${message}`
				}
				uni.showToast({
					title: message,
					icon: 'none'
				})
			} else {
				let message = `找到 ${sortedTickets.length} 个车次`
				if (searchForm.departureDate) {
					const dateStr = new Date(searchForm.departureDate).toLocaleDateString()
					message = `${dateStr} ${message}`
				}
				uni.showToast({
					title: message,
					icon: 'success'
				})
			}
		}
		
		const addToCart = (ticket) => {
			cartStore.addToCart(ticket)
			uni.showToast({
				title: '已添加到购物车',
				icon: 'success'
			})
		}
		
		const navigateToCart = () => {
			uni.navigateTo({
				url: '../cart/cart'
			})
		}
		
		const getTrainType = (trainNumber) => {
			const type = trainNumber.charAt(0)
			switch(type) {
				case 'G': return '高铁'
				case 'D': return '动车'
				case 'K': return '快速'
				case 'Z': return '直达'
				default: return '普通'
			}
		}
		
		const getTrainTagType = (trainNumber) => {
			const type = trainNumber.charAt(0)
			switch(type) {
				case 'G': return 'success'
				case 'D': return 'primary'
				case 'K': return 'warning'
				case 'Z': return 'info'
				default: return ''
			}
		}
		
		const disabledDate = (time) => {
			return time.getTime() < Date.now() - 8.64e7
		}
		
		// 清除日期选择
		const clearDate = () => {
			searchForm.departureDate = ''
			searchTickets()
		}
		
		// 添加日期格式化函数
		const formatDate = (date) => {
			if (!date) return ''
			const d = new Date(date)
			const month = d.getMonth() + 1
			const day = d.getDate()
			const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
			const weekday = weekdays[d.getDay()]
			return `${month}月${day}日 ${weekday}`
		}

		// 添加日期选择器相关方法
		const showDatePicker = () => {
			uni.showToast({
				title: '请选择日期',
				icon: 'none'
			})
		}

		// 添加站点选择相关的状态和方法
		const stationPickerVisible = ref(false)
		const currentPickerType = ref('')
		const pickerTitle = computed(() => 
			currentPickerType.value === 'departure' ? '选择出发站' : '选择到达站'
		)

		// 热门城市列表
		const hotCities = [
			'北京', '上海', '广州', '深圳', 
			'杭州', '南京', '武汉', '成都'
		]

		// 所有城市列表（从车票数据中提取）
		const allCities = computed(() => {
			const cities = new Set()
			allTickets.value.forEach(ticket => {
				cities.add(ticket.departure)
				cities.add(ticket.arrival)
			})
			return Array.from(cities).sort()
		})

		// 显示站点选择器
		const showStationPicker = (type) => {
			currentPickerType.value = type
			stationPickerVisible.value = true
		}

		// 选择站点
		const selectStation = (city) => {
			if (currentPickerType.value === 'departure') {
				searchForm.departure = city
			} else {
				searchForm.arrival = city
			}
			stationPickerVisible.value = false
			// 如果两个站点都已选择，自动搜索
			if (searchForm.departure && searchForm.arrival) {
				searchTickets()
			}
		}

		return {
			searchForm,
			tickets,
			allTickets,
			hasSearched,
			hotRoutes,
			recommendedTickets,
			cartCount: computed(() => cartStore.count),
			ArrowRight,
			Switch,
			ShoppingCart,
			switchStations,
			searchTickets,
			addToCart,
			navigateToCart,
			getTrainType,
			getTrainTagType,
			disabledDate,
			selectHotRoute,
			clearDate,
			formatDate,
			showDatePicker,
			stationPickerVisible,
			pickerTitle,
			hotCities,
			allCities,
			showStationPicker,
			selectStation,
			ArrowDown
		}
	}
}
</script>

<style scoped>
.container {
	background: #f5f7fa;
	min-height: 100vh;
}

/* 顶部搜索区域 */
.search-header {
	background: linear-gradient(135deg, #2b85e4 0%, #2d8cf0 100%);
	padding: 20px 15px;
	color: #fff;
}

.station-switch {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20px;
}

.station-item {
	flex: 1;
}

.station-label {
	font-size: 12px;
	opacity: 0.8;
	margin-bottom: 4px;
}

.station-value {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.placeholder {
	color: rgba(255,255,255,0.6);
}

.switch-btn {
	width: 32px;
	height: 32px;
	background: rgba(255,255,255,0.2);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 0 15px;
}

.date-picker {
	margin-bottom: 20px;
}

.date-label {
	font-size: 12px;
	opacity: 0.8;
	margin-bottom: 4px;
}

.date-value {
	font-size: 16px;
}

.search-btn {
	width: 100%;
	height: 44px;
	font-size: 16px;
	border-radius: 22px;
	background: #fff;
	color: #2d8cf0;
	border: none;
}

/* 热门路线 */
.section-title {
	padding: 15px;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.title-text {
	font-size: 16px;
	font-weight: 500;
	color: #333;
}

.title-desc {
	font-size: 12px;
	color: #999;
}

.hot-routes {
	padding: 0 15px;
}

.hot-route-item {
	background: #fff;
	border-radius: 8px;
	padding: 15px;
	margin-bottom: 10px;
}

.route-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8px;
}

.route-stations {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 16px;
	color: #333;
}

.route-tag {
	font-size: 12px;
	color: #2d8cf0;
	background: rgba(45,140,240,0.1);
	padding: 2px 8px;
	border-radius: 10px;
}

.route-desc {
	font-size: 12px;
	color: #999;
}

/* 搜索结果 */
.result-header {
	background: #fff;
	padding: 15px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #f0f0f0;
}

.result-date {
	font-size: 16px;
	font-weight: 500;
	color: #333;
}

.result-count {
	font-size: 12px;
	color: #999;
}

.ticket-list {
	padding: 10px 15px;
}

.ticket-item {
	background: #fff;
	border-radius: 8px;
	padding: 15px;
	margin-bottom: 10px;
}

.ticket-main {
	margin-bottom: 15px;
}

.time-info {
	display: flex;
	align-items: center;
	margin-bottom: 15px;
}

.departure, .arrival {
	flex: 1;
}

.time {
	font-size: 20px;
	font-weight: 500;
	color: #333;
	margin-bottom: 4px;
}

.station {
	font-size: 12px;
	color: #666;
}

.duration {
	padding: 0 15px;
	text-align: center;
}

.duration-line {
	height: 1px;
	background: #e0e0e0;
	position: relative;
	margin: 10px 0;
}

.duration-line::before,
.duration-line::after {
	content: '';
	position: absolute;
	width: 4px;
	height: 4px;
	border-radius: 50%;
	background: #e0e0e0;
	top: -1.5px;
}

.duration-line::before {
	left: 0;
}

.duration-line::after {
	right: 0;
}

.duration-text {
	font-size: 12px;
	color: #999;
}

.train-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.train-number {
	font-size: 14px;
	color: #666;
}

.train-type {
	font-size: 12px;
	color: #2d8cf0;
	margin-left: 5px;
}

.seats-info {
	font-size: 12px;
	color: #666;
}

.seats-info.low {
	color: #ff4d4f;
}

.ticket-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 15px;
	border-top: 1px solid #f0f0f0;
}

.price {
	display: flex;
	align-items: baseline;
}

.price-symbol {
	font-size: 14px;
	color: #ff4d4f;
}

.price-value {
	font-size: 24px;
	font-weight: 500;
	color: #ff4d4f;
}

.book-btn {
	width: 80px;
	height: 32px;
	border-radius: 16px;
}

/* 购物车按钮 */
.cart-fab {
	position: fixed;
	right: 20px;
	bottom: 20px;
	width: 44px;
	height: 44px;
	background: #2d8cf0;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	box-shadow: 0 4px 12px rgba(45,140,240,0.4);
}

/* 空状态 */
.empty-result {
	padding: 60px 0;
	text-align: center;
}

.empty-icon {
	width: 120px;
	height: 120px;
	margin-bottom: 15px;
}

.empty-text {
	font-size: 14px;
	color: #999;
}

/* 添加日期选择器样式 */
.date-picker-input {
	width: 100%;
	:deep(.el-input__wrapper) {
		background: rgba(255,255,255,0.1);
		border: none;
	}
	:deep(.el-input__inner) {
		color: #fff;
		font-size: 16px;
	}
	:deep(.el-input__prefix-inner) {
		color: rgba(255,255,255,0.8);
	}
}

/* 站点选择器样式 */
:deep(.station-picker-dialog) {
	border-radius: 12px;
	margin: 0 15px;
}

.station-picker {
	max-height: 60vh;
	overflow-y: auto;
}

.picker-section {
	margin-bottom: 20px;
}

.section-title {
	font-size: 14px;
	color: #999;
	margin-bottom: 10px;
}

.hot-cities {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 10px;
}

.city-list {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 10px;
}

.city-item {
	text-align: center;
	padding: 10px;
	background: #f5f7fa;
	border-radius: 4px;
	font-size: 14px;
	color: #333;
}

.city-item:active {
	background: #e6f1fc;
	color: #2d8cf0;
}
</style>
